package ttelectronic.mobileholder.service;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import ttelectronic.mobileholder.common.MHCommon;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.util.Log;

public class MHMissCallService extends Thread {

	private OutputStream mOutStream;
	private Handler mHandler;
	private Context mContext;
	private int mState;

	public MHMissCallService(Context context, Handler handler,
			BluetoothSocket socket) {
		mContext = context;
		mHandler = handler;
		mState = 0;
		try {
			mOutStream = socket.getOutputStream();
			Log.d(MHCommon.TAG + " MHMissCallService",
					"getOutputStream() successfully");
		} catch (IOException e) {
			Log.d(MHCommon.TAG + " MHMissCallService",
					"Can not getOutputStream()");
		}
	}

	public void run() {
		super.run();
		while (true) {
			final String[] projection = null;
			final String selection = null;
			final String[] selectionArgs = null;
			final String sortOrder = android.provider.CallLog.Calls.DATE
					+ " DESC";
			Cursor cursor = null;
			int sum = 0;
			try {
				cursor = mContext.getContentResolver().query(
						Uri.parse("content://call_log/calls"), projection,
						selection, selectionArgs, sortOrder);
				while (cursor.moveToNext()) {
					String callType = cursor
							.getString(cursor
									.getColumnIndex(android.provider.CallLog.Calls.TYPE));
					String isCallNew = cursor
							.getString(cursor
									.getColumnIndex(android.provider.CallLog.Calls.NEW));
					if (Integer.parseInt(callType) == CallLog.Calls.MISSED_TYPE
							&& Integer.parseInt(isCallNew) > 0) {
						sum += 1;
					}
				}
				if (sum > 0) {
					Log.d(MHCommon.TAG + "MHMissCallService",
							"Missed Call Found: " + sum);
					PrintWriter pWriter = new PrintWriter(
							new OutputStreamWriter(mOutStream));
					pWriter.write(MHCommon.POSTMSG_MISSED_CALL);
					pWriter.flush();
					mState = 1;

				} else {
					if (mState == 1) {
						PrintWriter pWriter = new PrintWriter(
								new OutputStreamWriter(mOutStream));
						pWriter.write(MHCommon.POSTMSG_NO_MISSED_CALL);
						pWriter.flush();
						Log.d(MHCommon.TAG + "MHMissCallService",
								"No missed call found");
						mState = 0;
					}
				}

				Message msg = mHandler
						.obtainMessage(MHCommon.MESSAGE_MISS_CALL);
				Bundle bundle = new Bundle();
				bundle.putString(MHCommon.BUNDLE_MISS_CALL, sum + "");
				msg.setData(bundle);
				mHandler.sendMessage(msg);
				Thread.sleep(1000);

			} catch (Exception ex) {
				Log.d(MHCommon.TAG + "MHMissCallService", "error");
			}
		}
	}

}
